package cn.afactory.tygz.ui.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.harwkin.nb.popmenu.PopupButton;
import com.harwkin.nb.popmenu.adapter.ServiceTypeAdapter;

import java.util.ArrayList;
import java.util.List;

import cn.afactory.tygz.R;
import cn.afactory.tygz.controller.CommunityController;
import cn.afactory.tygz.model.LifeServiceInfo;
import cn.afactory.tygz.model.LifeServiceInfoList;
import cn.afactory.tygz.model.SecondGoodsInfo;
import cn.afactory.tygz.model.ServiceTypeList;
import cn.afactory.tygz.ui.activities.LifeServiceDetailActivity;
import cn.afactory.tygz.ui.adapter.LifeServiceListAdapter;
import cn.afactory.tygz.ui.base.BaseFragment;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshBase;
import cn.afactory.tygz.ui.base.thirdpart.pulltorefresh.PullToRefreshListView;
import cn.afactory.tygz.ui.base.utils.LocalUtils;
import cn.afactory.tygz.ui.base.utils.SPUtils;

public class LifeServiceListFragment extends BaseFragment {
    private static final String TAG = LifeServiceListFragment.class.getSimpleName();
    protected CommunityController mController;
    protected LifeServiceListAdapter mAdapter;

    protected int mPageIndex = 1;
    protected int mPageSize = 10;
    private PopupButton mPbClass;
    private List<LifeServiceInfo> mList = new ArrayList<>();
    public LifeServiceListFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mController = new CommunityController(mContext, mUIHandler, null);
    }

    @Override
    public View onCreateViewCustom(LayoutInflater inflater, ViewGroup container) {
        View mlayout = inflater.inflate(R.layout.fg_life_service_list, null);
        initViews(mlayout);
        showTitleBar(false);

        mController.loadServiceTypeList(1);
        return mlayout;
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case CommunityController.MSG_GET_LIFE_SERVICE_LIST_OK:
                if (msg.obj instanceof LifeServiceInfoList) {
                    hideErrorPage(-1);
                    LifeServiceInfoList t = (LifeServiceInfoList) msg.obj;
                    if (t.value != null && t.value.size() >= 0) {
                        if(mAdapter.getCount() == 0 && t.value.size() == 0){
                            showNullPage(true);
                            return ;
                        }
                        try {
                            mList.addAll(t.value);
                            mAdapter.setData(mList);
                            mPageIndex = (mList.size()/mPageSize) + 1;
                            setListListener();

                            if (plistview.isRefreshing()) {
                                plistview.onRefreshComplete();
                            }
                            if (t.value.size() < mPageSize) {
                                plistview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                            } else {
                                plistview.setMode(PullToRefreshBase.Mode.BOTH);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        if (mAdapter.getCount() == 0) {
                            showNullPage(true);
                        }
                    }
                }
                break;
            case CommunityController.MSG_GET_LIFE_SERVICE_LIST_KO:
                if (mAdapter.getCount() == 0) {
                    hideErrorPage(-1);
                    showErrorPage(msg.arg1, new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            startLoadData(true);
                        }
                    });
                } else {
                    LocalUtils.showToast(mContext, (String) msg.obj);
                }
                break;
            case CommunityController.MSG_GET_SERVICE_TYPE_OK:
                handleServiceType((ServiceTypeList)msg.obj);
                break;
            case CommunityController.MSG_GET_SERVICE_TYPE_KO:
                mPbClass.setVisibility(View.GONE);
                break;
        }

        // 结束下拉刷新
        if (plistview.isRefreshing()) {
            plistview.onRefreshComplete();
        }
    }

    private void handleServiceType(final ServiceTypeList t){
        hideErrorPage(-1);
        if (t.value != null && t.value.size() >= 0) {
            if(t.value.size() == 0){
                mPbClass.setVisibility(View.GONE);
                return ;
            }

            //类型
            typeAdapter = new ServiceTypeAdapter(getActivity(),R.layout.popup_item,t.value,R.drawable.pb_list_item_normal,R.drawable.pb_list_item_press);
            typeLv.setAdapter(typeAdapter);
            typeLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    typeAdapter.setPressPostion(position);
                    typeAdapter.notifyDataSetChanged();
                    mPbClass.setText(t.value.get(position).typeName);
                    mPbClass.hidePopup();
                    reloadDatas(t.value.get(position).typeId);
                }
            });
            mPbClass.setPopupView(typeView);
        }
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        startLoadData(true);
    }

    /**
     * 初始化组件 views
     *
     * @param view
     */
    private void initViews(View view) {
        plistview = (PullToRefreshListView) view.findViewById(R.id.plv_subject);
        mPbClass = (PopupButton)view.findViewById(R.id.pb_class);
        initListView();
        initPbDatas();
    }
    private int mTypeId = 0;
    private ServiceTypeAdapter typeAdapter;
    private View typeView;
    private ListView typeLv;
    private void initPbDatas(){
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        typeView = inflater.inflate(R.layout.sub_second_goods_class, null);
        typeLv = (ListView) typeView.findViewById(R.id.lv);
    }

    private void reloadDatas(int typeId){
        mTypeId = typeId;
        startLoadData(true);
    }

    /**
     * 加载listview数据
     */
    protected void startLoadData(boolean cleanData) {
        if (cleanData) {
            mPageIndex = 1;
            mList.clear();
        }
        double lat = 0;
        double lng = 0;
        if(SPUtils.getExtraCurrentLat(getActivity()) != null){
            lat = Double.parseDouble(SPUtils.getExtraCurrentLat(getActivity()));
        }

        if(SPUtils.getExtraCurrentLon(getActivity()) != null){
            lng = Double.parseDouble(SPUtils.getExtraCurrentLon(getActivity()));
        }
        mController.loadLifeServiceList(lat, lng, mTypeId, mPageIndex, mPageSize);
    }

    /**
     * 初始化list view
     */
    private void initListView() {
        mAdapter = new LifeServiceListAdapter(mContext,null);
        plistview.setAdapter(mAdapter);
        mAdapter.setData(mList);
        plistview.setMode(PullToRefreshBase.Mode.BOTH);
        setListListener();
        plistview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadData(true);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                startLoadData(false);
            }
        });
    }

    protected void setListListener() {
        plistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListView lv = plistview.getRefreshableView();
                if (position >= lv.getHeaderViewsCount()) {
                    position -= lv.getHeaderViewsCount();
                }
                Intent intent = new Intent(mContext, LifeServiceDetailActivity.class);
                LifeServiceInfo lifeServiceInfo = (LifeServiceInfo)mAdapter.getItem(position);
                intent.putExtra(LifeServiceDetailActivity.EXT_DATA_TAG, lifeServiceInfo);
                startActivity(intent);
            }
        });
    }
    //跳转到物品详情
    private void gotoSecondGoodsDetailPage(SecondGoodsInfo secondGoodsInfo){
        if(secondGoodsInfo == null || secondGoodsInfo.id <= 0){
            return;
        }
        try{
//            mContext.startActivity(UserHomeActivity.getIntent(mContext, snsUserInfo.userId));
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

//    private List<LifeServiceInfo> generateTestData(){
//        List<LifeServiceInfo> lifeServiceInfos = new ArrayList<>();
//
//        LifeServiceInfo lifeServiceInfo = new LifeServiceInfo();
//        lifeServiceInfo.id = 1;
//        lifeServiceInfo.distance = "距离：10公里";
//        lifeServiceInfo.price = "人均：50";
//        lifeServiceInfo.title = "中国银行新惠支行";
//        lifeServiceInfo.image = "";
//        lifeServiceInfo.type = "类型：ATM";
//
//        lifeServiceInfos.add(lifeServiceInfo);
//        lifeServiceInfos.add(lifeServiceInfo);
//        lifeServiceInfos.add(lifeServiceInfo);
//        lifeServiceInfos.add(lifeServiceInfo);
//        lifeServiceInfos.add(lifeServiceInfo);
//        lifeServiceInfos.add(lifeServiceInfo);
//        lifeServiceInfos.add(lifeServiceInfo);
//
//        return lifeServiceInfos;
//    }
}
